<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Validation exceptions.
 */
class Validation_Exception extends Kohana_Exception {
	
	/**
	* Array of validation objects
	* @var array
	*/
	protected $_objects = array();

	/**
	* The alias of the main ORM model this exception was created for
	* @var string
	*/
	protected $_alias = NULL;
	
	/**
	 * Constructs a new exception for the specified model
	 *
	 * @param  string     $alias       The alias to use when looking for error messages
	 * @param  Validation $object      The Validation object of the model
	 * @param  string     $message     The error message
	 * @param  array      $values      The array of values for the error message
	 * @param  integer    $code        The error code for the exception
	 * @return void
	 */
	public function __construct($alias, Validation $object, $message = 'Failed to validate array', array $values = NULL, $code = 0)	{
		$this->_alias = $alias;
		$this->_objects['_object'] = $object;
		$this->_objects['_has_many'] = FALSE;
		parent::__construct($message, $values, $code);
	}
	
	public function errors($directory = "a", $translate = TRUE) {
		// TODO first parameter, "file", cannot be NULL to translate errors messages
		return $this->generate_errors($this->_alias, $this->_objects, $directory, $translate);
	}

	/**
	 * Recursive method to fetch all the errors in this exception
	 *
	 * @param  string $alias     Alias to use for messages file
	 * @param  array  $array     Array of Validation objects to get errors from
	 * @param  string $directory Directory to load error messages from
	 * @param  mixed  $translate Translate the message
	 * @return array
	 */
	protected function generate_errors($alias, array $array, $directory, $translate) {
		$errors = array();
		foreach ($array as $key => $object) {
			if (is_array($object)) {
				$errors[$key] = $this->generate_errors($key, $object, $directory, $translate);
			} elseif ($object instanceof Validation) {
				if ($directory === NULL) {
					// Return the raw errors
					$file = NULL;
				} else {
					$file = trim($directory.'/'.$alias, '/');
				}
				// Merge in this array of errors
				$errors += $object->errors($file, $translate);
			}
		}
		return $errors;
	}
}